package lgkj.meicqt20.ui;

import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import lgkj.meicqt20.R;
import lgkj.meicqt20.bean.MessageEvent;
import lgkj.meicqt20.utils.AllKindsOfConstant;
import lgkj.meicqt20.utils.HttpUtils;
import lgkj.meicqt20.utils.SharedPreferencesUtils;
import lgkj.meicqt20.view.NonLeakingWebView;

/**
 * Created by Administrator on 2019/1/24 0024.
 */

public class LoadUrlActivity extends BaseActivity {
    @BindView(R.id.webView)
    NonLeakingWebView mWebView;
    @BindView(R.id.iv_code)
    ImageView ivCode;
    @BindView(R.id.tv_name)
    TextView tvName;
    private String mMovieUrl;
    private int times;
    private int timeInterval = 0;
    private TimerTask task;
    private Timer timer;
    private SharedPreferencesUtils preferencesUtils;

    @Override
    public int setContentView() {
        return R.layout.activity_load_url;
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        Log.d(TAG, "onResume");
        HttpUtils.getQRCode(LoadUrlActivity.this, ivCode);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void DealEvent(MessageEvent messageEvent) {
        Log.i(TAG, "socket: " + messageEvent.toString());
        if ("control".equals(messageEvent.getTagName())) {
            if ("back".equals(messageEvent.getMessage())) {
                finish();
            } else if ("sure".equals(messageEvent.getMessage())) {
                clickView(mWebView, mWebView.getWidth() / 2, mWebView.getHeight() / 2);
            }
        }
    }

    public void clickView(View view, float x, float y) {
        WebView v = (WebView) view;
        Log.i(TAG, "clickView: " + v.getUrl() + "\n" + mMovieUrl);
        long downTime = SystemClock.uptimeMillis();
        final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_DOWN, x, y, 0);
        downTime += 10;
        final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_UP, x, y, 0);
        view.onTouchEvent(downEvent);
        view.onTouchEvent(upEvent);
        downEvent.recycle();
        upEvent.recycle();
    }

    @Override
    public void init() {
        activitiesList.add(this);
        displayDifferen();
        times = 0;
        preferencesUtils = new SharedPreferencesUtils(LoadUrlActivity.this);
        timeInterval = getIntent().getIntExtra("video_time", timeInterval);
        String name = getIntent().getStringExtra("video_name");
        if (name != null && !"".equals(name)) {
            tvName.setText(name);
        }
        mMovieUrl = getIntent().getStringExtra("mMovieUrl");
//        mMovieUrl = "http://vod.05948166.com/05948166.php?url=https://v.youku.com/v_show/id_XMzczNDMyODEwOA==.html?spm=a2h03.8164468.2069756.1";
//        mMovieUrl = "http://vod.05948166.com/05948166.php?url=http://v.qq.com/x/cover/2u9eoilyg7q8i0q.html";
        WebSettings ws = mWebView.getSettings();
        /**
         *
         * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
         * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
         * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
         * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
         * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
         * setSupportZoom 设置是否支持变焦
         * */
        ws.setAllowFileAccess(true);
        ws.setAllowFileAccess(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);  //非https得资源
        }

        ws.setSupportMultipleWindows(true);// 新加
        ws.setPluginState(WebSettings.PluginState.ON);
        ws.setBuiltInZoomControls(true);// 隐藏缩放按钮
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
        ws.setUseWideViewPort(true);// 可任意比例缩放
        ws.setLoadWithOverviewMode(true);// setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式。
        ws.setSavePassword(true);
        ws.setSaveFormData(true);// 保存表单数据
        ws.setJavaScriptEnabled(true);
        ws.setGeolocationEnabled(true);// 启用地理定位
        ws.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");// 设置定位的数据库路径
        ws.setCacheMode(WebSettings.LOAD_NO_CACHE);
        ws.setDomStorageEnabled(true);
        mWebView.clearHistory();
        mWebChromeClient mWebchromeclient = new mWebChromeClient();
        mWebView.setWebChromeClient(mWebchromeclient);
        mWebView.setWebViewClient(new MyClient());
//        mWebView.loadUrl("http://www.le.com/ptv/vplay/28598552.html?ref=100000001");//乐视
        if (!mMovieUrl.equals("")) {
            mWebView.loadUrl(mMovieUrl);//乐视
        }

        Log.d(TAG, ",timer:" + timeInterval + "mMovieUrl:" + mMovieUrl);
        closeActitity();
    }

    private void closeActitity() {
        if (timer == null) {
            timer = new Timer();
        }
        if (task != null) {
            return;
        }
        if (timeInterval == 0) {
            return;
        }
        preferencesUtils.setParam("homeback", false);
        task = new TimerTask() {
            @Override
            public void run() {
                times = times + 1;
                Log.d(TAG, "定时任务开启，总共" + timeInterval + "分钟，第" + times + "分钟，");
                if ((times - timeInterval) > 3) {
                    for (int i = 0; i < AllKindsOfConstant.activitiesList.size(); i++) {
                        if (AllKindsOfConstant.activitiesList.get(i) != null) {
                            AllKindsOfConstant.activitiesList.get(i).finish();
                            //关闭
                            Log.i(TAG, "关闭这个activity成功~：  " + AllKindsOfConstant.activitiesList.get(i).getLocalClassName());
                        }
                    }
                }
            }
        };
        timer.scheduleAtFixedRate(task, 0, 1 * 60 * 1000);
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public class mWebChromeClient extends WebChromeClient {

        @Override
        //播放网络视频时全屏会被调用的方法
        public void onShowCustomView(View view, CustomViewCallback callback) {
            mWebView.setMinimumHeight(800);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        @Override
        //视频播放退出全屏会被调用的
        public void onHideCustomView() {
        }
    }

    public class MyClient extends WebViewClient {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            Log.i(TAG, "shouldInterceptRequest: " + request.toString());
//            request = null;
            return super.shouldInterceptRequest(view, request);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            url = url.toLowerCase();
            Log.i(TAG, "shouldInterceptRequest url=" + url + ";threadInfo" + Thread.currentThread());
            WebResourceResponse response = null;
            if (url.contains(".baidu.com")) {
                try {
                    InputStream localCopy = getAssets().open("bdjp_small.png");
                    response = new WebResourceResponse("image/png", "UTF-8", localCopy);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return response;


        }

        public boolean hasAd(String url) {
            String adUrls = "md.05948166.com";
            if (url.contains(adUrls)) {
                return true;
            }
            return false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearCacheFolder();
        preferencesUtils.setParam("homeback", true);
        if (mWebView != null) {
            mWebView.onPause();
            mWebView.removeAllViews();
            mWebView.destroy();
        }
        if (task != null) {
            task.cancel();
            Log.d(TAG, "onDestroy: 停止定时任务");
        }
        if (timer != null) {
            times = 0;
            timer.cancel();
            Log.d(TAG, "onDestroy: 停止定时任务");
        }
    }


    private void clearCacheFolder() {
        CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();

        //String testcookie1 = cookieManager.getCookie(urlpath);

        cookieManager.removeAllCookie();
        cookieSyncManager.sync();

        //String testcookie2 = cookieManager.getCookie(urlpath);
    }
}
